require 'digest/sha1'
class User < ActiveRecord::Base
  
  has_many :roleships, :dependent => :delete_all
  has_many :roles, :through => :roleships
  
  validates_presence_of   :name
  validates_uniqueness_of :name
  
  after_save :create_roleship, :set_the_first_user_as_admin
  
  cattr_reader :per_page
  @@per_page = 20
  
  attr_accessor :password_confirmation
  validates_confirmation_of :password
  
  def validate
    errors.add_to_base("Missing password") if hashed_password.blank?
  end

  
  def self.authenticate(name,password)
    user = self.find_by_name(name)
    if user
      expected_password = encrypted_password(password,user.salt)
      if user.hashed_password != expected_password
        user = nil
      end
    end
    user
  end
  
  def password
    @password
  end
  
  def password=(pwd)
    @password = pwd
    return if pwd.blank?
    create_new_salt
    self.hashed_password = User.encrypted_password(self.password, self.salt)
  end
  
  def admin?
    return true if find_roleship(Role.admin.id)
    return false
  end
  
  def power_user?
    return true if find_roleship(Role.power_user.id)
    return false
  end
  
  def guest?
    return true if find_roleship(Role.guest.id)
    return false
  end
  
  def set_role(id)
    roleships = Roleship.find_all_by_user_id(self.id)
    for r in roleships do
      r.destroy
    end
    roleship = Roleship.new(:role_id => id, :user_id => self.id)
    roleship.save
  end
  
  private
  
  def create_roleship
    unless Roleship.find_by_user_id(self.id)
      @roleship = Roleship.new(:user_id => self.id, :role_id => Role.guest.id)
      @roleship.save
    end
  end
  
  def set_the_first_user_as_admin
    if 1 == User.find(:all).size
      Roleship.find_by_id(self.id).destroy
      roleship = Roleship.new(:user_id => self.id, :role_id => Role.admin.id )
      roleship.save
    end
  end
  
  
  def self.encrypted_password(password, salt)
    string_to_hash = password + "wibble" + salt
    Digest::SHA1.hexdigest(string_to_hash)
  end
  
  def find_roleship(id)
    Roleship.find_by_user_id_and_role_id(self.id, id)
  end
  
  def create_new_salt
    self.salt = self.object_id.to_s + rand.to_s
  end
end
